package org.goldfish.chatroom.controller;

import org.goldfish.chatroom.entity.PublicNetworkService;
import org.goldfish.chatroom.mapper.PublicNetworkServiceMapper;
import org.goldfish.chatroom.service.PublicNetworkServiceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.health.HealthEndpointProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("info/update")
public class InfoUpdateController {

    @Autowired
    private PublicNetworkServiceManager manager;

    /**
     * logger
     */
    private static final org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(InfoUpdateController.class);

    @GetMapping
    public String updateInfo(
            Model model,
            @RequestParam(
                    name = "service_name",
                    defaultValue = "__name__"
            )
            String service_name) {
        try {
            PublicNetworkService publicNetworkService = manager.getPublicNetworkServiceByName(service_name);
            model.addAttribute("service", publicNetworkService);
            return "update";
        } catch (Exception e) {
            logger.warn("Failed to get network service", e);
            model.addAttribute("error", e.getMessage());
            return "error";
        }
    }

    @PostMapping
    public String updateInfo(
            @RequestParam(
                    name = "name"
            )
            String service_name,
            @RequestParam(
                    name = "domain"
            )
            String domain,
            @RequestParam(
                    name = "port",
                    defaultValue = ""
            )
            String port) {
        try {
            manager.updatePublicNetworkService(service_name, domain, port, true);
            return "redirect:../info";
        } catch (Exception e) {
            logger.warn("Failed to update network service", e);
            return "error";
        }
    }

}
